import 'package:chat/common/model/User.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../../common/model/ChatList.dart';
import '../../../common/service/HttpService.dart';
import '../../../common/utils/storage.dart';

class SearchchatController extends GetxController {
  SearchchatController();

  var user = Rxn<UserModel>();
  final TextEditingController searchMessageContentController = TextEditingController();

  var searchUserList = <ChatList>[].obs;
  RxString hasSearch = "请输入内容搜索聊天".obs;

  _initData() {
    update(["searchchat"]);
  }

  Future<void> fetchData() async {
    try {
      String searchContent = searchMessageContentController.text.trim();
      if (searchContent.isEmpty) {
        searchUserList.clear();
        hasSearch.value = "请输入内容搜索聊天";
        return;
      }

      UserModel? user = await Storage().getUser();
      final response = await HttpService.to.get("/user-message/list/search", query: {"userId": user!.uid, "content": searchContent});

      if (response.statusCode == 200 && response.data["code"] == 200) {
        final List<dynamic> list = response.data["data"] ?? [];
        searchUserList.value = list.map((e) => ChatList.fromJson(e)).toList();
        print("✅ 搜索结果: ${searchUserList.length} 条");
      } else {
        searchUserList.clear();
        hasSearch.value = "未找到匹配的聊天记录";
      }
    } catch (e) {
      print("搜索聊天消息错误: $e");
    }
  }

  @override
  void onInit() async {
    super.onInit();
    user.value = await Storage().getUser();
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  @override
  void onClose() {
    super.onClose();
    searchMessageContentController.clear();
  }
}
